package com.entrogy.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.Msg;
import com.entrogy.controller.DormController;
import com.entrogy.utils.constants.ErrorEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName SessionCheckFilter
 * @Description
 * @Author luoxingjiang
 * @Date 2019/8/26 0026 下午 2:45
 * @Version 1.0
 **/
@Component
public class SessionCheckFilter extends UserFilter {

    private static final Logger logger = LoggerFactory.getLogger(SessionCheckFilter.class);

    private static final String appId = "wx5fbf8057a88c5e45";


    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
//        //判断之前首先备份流，不然使用@Requestbody注解会由于流已经被读取而不能获取对象
//        ServletRequest requestWrapper = null;
//        try {
//             requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        // 小程序来的请求的话直接放开
        String requestReferer = ((HttpServletRequest)request).getHeader("Referer");
        if (StringUtils.isNoneBlank(requestReferer) && verifyRequestReferer(requestReferer)){
            return true;
        }
        // swagger请求也要放开
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        if ("/".equals(requestURI) || "/swagger-ui.html".equals(requestURI) || requestURI.startsWith("/webjars")
                || requestURI.startsWith("/swagger-resources") || requestURI.startsWith("/v2/api-docs")
                || requestURI.startsWith("/studentrecord/check") || requestURI.startsWith("/static") || requestURI.startsWith("/weixincore")){
            return true;
        }
        if (isLoginRequest(request, response)) {
            return true;
        } else {
            Subject subject = getSubject(request, response);
            // If principal is not null, then the user is known and should be allowed access.
            return subject.getPrincipal() != null;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        logger.info("用户登录超时，请求路径为=>" + ((HttpServletRequest) request).getRequestURI());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/JavaScript; charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(Msg.fail(ErrorEnum.E_20011, ErrorEnum.E_20011.getErrorMsg())));
        response.getWriter().flush();
        response.getWriter().close();
        return false;
    }

    public boolean verifyRequestReferer(String referer){
        String regEx = "^https://servicewechat.com/"+appId+"/(\\d+(\\.\\d+)?|devtools)/page-frame.html$";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(referer);
        return matcher.matches();
    }

}
